import mongodb from 'mongodb'
import config from '../../config'
let client = mongodb.MongoClient
let url = `mongodb://${config.mongodb.host}:${config.mongodb.port}/`

export function createDb(name) {
    return new Promise((resolve, reject) => {
        client.connect(url + name, (err, db) => {
            if(err)
                reject(err)
            else {
                db.close()
                resolve(name)

            }

        })
    })
}
export function dropCollection(dbname, collection) {
    return  new Promise((resolve, reject) => {
        client.connect(url + dbname, (err, db) => {
            if(err){
                reject(err)
            }else {
                let dbase = db.db(dbname)
                dbase.collection(collection).drop( (err, res) => {
                    if(err)
                        reject(err)
                    else {
                        db.close()
                        resolve(res)
                    }
                })
            }
        })
    })
}
export function createCollection(dbname, collection) {
    return  new Promise((resolve, reject) => {
        client.connect(url + dbname, (err, db) => {
            if(err){
                reject(err)
            }else {
                let dbase = db.db(dbname)
                dbase.createCollection(collection, (err, res) => {
                    if(err)
                        reject(err)
                    else {
                        db.close()
                        resolve(res)
                    }
                })
            }
        })
    })
}

export function mgodb(name, fn) {
    return new Promise((resolve, reject) => {
        client.connect(url + name, async (err, db) => {
            if(err)
                reject(err)
            else{
                let dbo = db.db(name)
                let res = await fn(dbo)
                db.close()
                resolve(res)
            }
        })
    })
}
export function mgoQuery(m) {
    return new Promise((resolve, reject) => {
        m.toArray((err,res) => {
            if(err){
                reject(err)
            }else {
                resolve(res)
            }
        })
    })
}
